<?php
// named Bricaboxcontroller to avoid class name conflict with Bricabox library
class Bricaboxcontroller extends Controller {
	function Bricaboxcontroller()
	{
		parent::Controller();
	}
	
	function show()
	{
		// handled in route_router#index
	}
	
	function title_results()
	{
		$this->load->database();
		
		$id 	= $this->uri->segment(2);
		$value  = $this->input->post('q');
		
		$ret   = array("Add <span class=\"suite\">{$value}</span> as a new entry");
		$query = $this->db->query('select id,field1_value from contents
			where bricabox_id = ? and field1_value like ?', array($id, "%{$value}%"));
		if ($query->num_rows())
			foreach ($query->result() as $content)
				$ret[] = '<span class="suite">'.$content->field1_value.'</span>&nbsp;<a onclick="location.href=\'/content/'.$content->id.'\';" href="/content/'.$content->id.'">View entry &rarr;</a>';
				
		echo join("\n", $ret);
	}
	
	// this action will always be POSTed to from an admin screen
	function save()
	{
		// 404 if the current user isn't authorized
		global $BBX;
		$this->load->model('Membership_model');
		if (!isset($BBX['bricabox'])
			|| !$this->userland->logged_in()
			|| ($this->userland->logged_in() && !$this->Membership_model->is_owner($BBX['bricabox']->id,
																					$this->userland->current_user()->id)
			)
		)
		{
			show_404();
			exit();
		}
		
		$this->load->model('Bricabox_model');
		
		$id 	= $this->uri->segment(2);
		$params = $this->input->post('bricabox');
		if ($this->Bricabox_model->save($id, $params))
			$this->flashy->save_flash('notice', 'Great! Your settings have been saved.');
		else
			$this->flashy->save_flash('error', 'Something went wrong. Make sure you haven\'t left any fields blank.');
		header('Location: /admin/'.$this->input->post('section').'/'.$this->input->post('view'));
	}
	
	// this action will always be POSTed to from an admin screen
	function save_interaction()
	{
		// 404 if the current user isn't authorized
		global $BBX;
		$this->load->model('Membership_model');
		if (!isset($BBX['bricabox'])
			|| !$this->userland->logged_in()
			|| ($this->userland->logged_in() && !$this->Membership_model->is_owner($BBX['bricabox']->id,
																					$this->userland->current_user()->id)
			)
		)
		{
			show_404();
			exit();
		}
		
		$this->load->model('Bricabox_model');
		
		$id 	= $this->uri->segment(2);
		$type	= $this->input->post('int_hash');
		if ($type == 'none')
		{
			// disable interaction
			$this->Bricabox_model->save($id,
				array(
					'use_field2'		=> 20,
					'allow_engagement' 	=> "0"
				));
			$this->flashy->save_flash('notice', "Interaction has been turned off for this BricaBox.");
		}
		elseif ($type == 'fivestar')
		{
			// five star
			$this->Bricabox_model->save($id,
				array(
					'use_field2' 		=> 25,
					'engagement_type' 	=> 'fivestar',
					'allow_engagement' 	=> true
				));
			$this->flashy->save_flash('notice', "Your interaction settings have been changed to Five Star.");
		}
		elseif ($type == 'custom_terms')
		{
			$this->Bricabox_model->save($id,
				array(
					'use_field2' 		=> 33,
					'engagement_type' 	=> 'button',
					'allow_engagement' 	=> true,
					'engage_button_label' 	 => $this->input->post('engage_button_label'),
					'engage_term_past_tense' => $this->input->post('engage_term_past_tense')
				));
			$this->flashy->save_flash('notice', "Your interaction settings have been changed to custom.");
		}
		elseif (!in_array($type, array('none', 'fivestar', 'custom_terms')))
		{
			// button style, so extract terms from the int_hash
			$eng_sql = array("allow_engagement = 1", "engagement_type = ?");
			$params  = array('button');
			
			$type  = url_safe_base64($type, 'decode');
			$terms = explode(',', $type);
			foreach ($terms as $term)
			{
				list($k, $v) = explode(':', $term);
				if ($k != 'id')
				{
					$eng_sql[] = "$k = ?";
					$params[]  = $v;
				}
			}
			$eng_sql  = implode(',', $eng_sql);
			$params[] = $id;
			$this->db->query("update bricaboxes set {$eng_sql}
				where id = ?", $params);
			$this->flashy->save_flash('notice', "Your interaction settings have been saved.");
		}
		header('Location: /admin/'.$this->input->post('section').'/'.$this->input->post('view'));
	}
	
	function custom_css()
	{
		global $BBX;
		
		$bricabox = $BBX['bricabox'];
		
		// calculate the theme_id we might need to use
		if (!$bricabox->theme_id)
			$theme_id = 1;
		else
			$theme_id = $bricabox->theme_id;
			
		// using custom theme?
		$custom_theme = false;
		if (in_array($bricabox->customize_with, array('none', 'theme')))
		{
			$this->load->model("Theme_model");
			
			$custom_theme = true;
			
			$theme 		= $this->Theme_model->load_theme($theme_id);
			$theme_dir 	= BASEPATH."../assets/themes/".url_title($theme->name, 'underscore')."/";
		}
		
		// we want to pass a text/css mime type
		$this->output->set_header('Content-type: text/css');
		
		// build css for a custom color scheme
		$colors = array();
		
		$data = array(
			'with' 		=> $bricabox->customize_with,
			'colors' 	=> $colors,
			'bricabox' 	=> $bricabox,
			'theme_id'	=> $theme_id,
		);
		
		if ($custom_theme)
		{
			$data['theme'] 		= $theme;
			$data['theme_dir']  = $theme_dir;
		}
		
		$this->load->view('bricabox/custom_css', $data);
	}
	
	function members()
	{
		//$this->output->cache(60); // 60 min TTL
		
		global $BBX;
		
		$this->load->model('Bricabox_model');
		$this->load->model('Block_model');
		$this->load->model('Content_model');
		$this->load->model('Membership_model');
		
		ini_set('display_errors', 'on');
		$data = array(
			'BBX'			=> $BBX,
			'bricabox' 		=> $BBX['bricabox'],
			'page_title'	=> $BBX['bricabox']->name.": Members",
			'members'		=> $this->Membership_model->get_members_of($BBX['bricabox']->id)
		);
		$this->load->view('bricabox/members', $data);
	}
	
	// take an ajax request from a block instance and pass it off to the appropriate handler;
	// handlers should return html to inject back into the view
	//
	// todo: remove all the sql from this action!
	function block_proxy()
	{
		$this->load->model('Block_model');
		
		$inst_id	 = $this->input->post('instance_id');
		$bricabox_id = $this->uri->segment(2);
		$parent		 = $this->Block_model->get_parent($inst_id);
		$parent_name = $parent->name;
		$tpl_path	 = BlockInstance::get_template_path($parent_name);
		$klass 		 = BlockInstance::load_block_file(
			$tpl_path,
			$parent_name
		);
		$instance = $this->Block_model->get_instance($inst_id);
		
		$_return = $klass->handle_proxy($bricabox_id, $_REQUEST, $parent_name, $tpl_path, $instance, $parent);
		
		echo $_return;
	}
	
	function handle_engagement()
	{
		// here's what we'll do:
		// 1. instantiate an instance of the proper engagement class
		// 2. invoke the proper callback (defaults to 'click')
		
		if (!$this->userland->logged_in())
			return false;
		
		$params = $this->input->post('eng');
		
		if (!isset($params['content_id']))
			return false; // probably not a POST
		
		global $BBX;
		
		$this->load->library('engagement');
		$this->load->model('Content_model');
		
		$type 		= isset($params['type']) ? $params['type'] : 'click';
		$klass 		= $this->engagement->engagement_for($BBX['bricabox']);
		$callback	= "on_{$type}";
		$_content	= $this->Content_model->load_content($params['content_id'], $BBX['bricabox']->id);
		
		// default value for non-fivestar is 3, to ease translation to and from fivestar (input median = 3)
		$value		= isset($params['value']) ? $params['value'] : 3;
		
		$klass->$callback($BBX['bricabox'], $_content, $this->userland->current_user(), $type, $value);
		
		// redirect back to the content?
		if (isset($params['redirect']))
			header("Location: {$params['redirect']}");
			
			//header("Location: /content/{$_content->id}");
	}
	
	function search()
	{
		
	}
	
	function encode_search()
	{
		echo url_safe_base64($this->input->post("value"), 'encode');
	}
	
	function sort_blocks()
	{
		$ids 		= $this->input->post('ids');
		$location 	= $this->input->post('location');
		$size		= $this->input->post('size');
		
		if (strlen($ids))
		{
			// strlen() of zero means the column is empty;
			// for each id, update its location and position
			$ids_ary = explode('~', $ids);
			foreach ($ids_ary as $pos => $id)
			{
				$pos++;
				$this->db->query('update block_instances
					set size_mode = ?, position = ?
					where bricabox_id = ? and id = ?',
				array($size, $pos, $this->uri->segment(2), $id));
			}
		}
		else
		{
			echo '';
		}
	}
	
	function add_block()
	{
		$this->load->model('Bricabox_model');
		
		$bricabox_id = $this->uri->segment(2);
		$cts 		 = $this->Bricabox_model->get_content_types($bricabox_id);
		
		$loc   = $this->input->post('location');
		$query = $this->db->query('select max(position)+1 as next_pos from block_instances
			where bricabox_id = ? and size_mode = ? and location = ?
			limit 1',
			array(
				$bricabox_id,
				$this->input->post('size'),
				$loc
			));
		$next_pos = $query->first_row()->next_pos;
		if ($next_pos < 1)
			$next_pos = 1;
		
		$query = $this->db->query('insert into block_instances
			(bricabox_id,block_id,size_mode,location,position)
			values(?,?,?,?,?)',
			array(
				$bricabox_id,
				$this->input->post('block_id'),
				$this->input->post('size'),
				$loc,
				$next_pos
			));
		$new_id = $this->db->insert_id();
		
		$query 		 = $this->db->query('select title from blocks where id = ? limit 1', array($this->input->post('block_id')));
		$block_title = $query->first_row()->title;
		
		$block_html = <<<HTML
<div class="block_instance" id="block_instance_{$new_id}">
	<h3><span class="title">{$block_title}</span>&nbsp;<span class="dragme">Drag this to reorder</span></h3>
	<div class="edit_block_links">
		<a href="#" onclick="return editTitle({$new_id});">Edit this block's title</a>
		or <a href="#" onclick="return removeBlock({$new_id});"><img src="/assets/images/icons/cross.png" alt="X" />
			Remove from layout</a>
HTML;

		if ($loc == 'content')
		{
			$block_html .= "<br />
<h3>Show this block for these kinds of entries:</h3>\n";
			foreach ($cts->result() as $ct)
			{
				$ct_name	 = ucfirst(Inflect::pluralize($ct->name));
				$field_id 	 = "exclude_{$new_id}_{$ct->id}";
				$block_html .= <<<HTML
	<input onclick="setExclusion({$new_id}, {$ct->id});" type="checkbox" id="{$field_id}" name="{$field_id}" value="1" checked="checked" />
		<label for="{$field_id}">{$ct_name}</label><br />
HTML;
			}
		}

		$block_html .= <<<HTML
	</div>
</div>
HTML;
		echo $block_html;
	}
	
	function remove_block()
	{
		$bricabox_id = $this->uri->segment(2);
		$id			 = $this->input->post('id');
		
		// remove via SQL
		$this->db->query('delete from block_instances
			where bricabox_id = ? and id = ? limit 1',
			array($bricabox_id, $id));
		
		echo '';
	}
	
	function save_title()
	{
		$bricabox_id = $this->uri->segment(2);
		$id			 = $this->input->post('id');
		
		$this->db->query('update block_instances
			set title = ?
			where bricabox_id = ? and id = ?',
			array($this->input->post('title'), $bricabox_id, $id));
		
		echo '';
	}
	
	function toggle_exclusion()
	{
		$bricabox_id = $this->uri->segment(2);
		$id			 = $this->input->post('id');
		$ct_id		 = $this->input->post('type_id');
		$value		 = $this->input->post('value');
		
		if ($value)
			$sql = "delete from block_exclusions where block_instance_id = ? and content_type_id = ?";
		else
			$sql = "insert into block_exclusions (block_instance_id, content_type_id) values(?,?)";
			
		$this->db->query($sql, array($id, $ct_id));
		
		echo '';
	}
	
	function save_block_prefs()
	{
		global $content;
		
		$bricabox_id = $this->uri->segment(2);
		$content_id	 = $this->input->post('content_id');
		$id			 = $this->input->post('id');
		$name		 = $this->input->post('name');
		$value		 = $this->input->post('value');
		$block_name	 = $this->input->post('block_name');
		
		require APPPATH.'libraries/blocks/block_instance.php';
		
		eval("
			\$brec 	   = new stdClass();
			\$brec->id = intval($id);
		");
		$bi	= BlockInstance::load_block_file(BlockInstance::get_template_path($block_name), $block_name);
		$bi->save_setting($brec, $name, $value, $content_id);
		
		$this->flashy->save_flash('notice', 'Super! Your settings have been saved.');
		$ret = $this->input->post('return_to');
		header("Location: {$ret}");
	}
	
	function private_home()
	{
		global $BBX;
		
		if ($this->_is_current_user_member())
			header("Location: /");
		
		// check privacy
		$this->load->model('Membership_model');
		if (!$BBX['bricabox']->privacy)
		{
			// make sure someone is logged in and a member
			if ($this->Membership_model->is_member($BBX['bricabox']->id))
			{
				header("Location: /");
			}
		}
		else
			header("Location: /");
		
		$this->load->view('bricabox/private', array('BBX' => $BBX));
	}
	
	function add_member()
	{
		global $BBX;
		
		if ($this->_is_current_user_member())
			header("Location: /");
		
		$this->load->model('Membership_model');
		
		$data['BBX'] = $BBX;
		
		if (!$this->userland->logged_in() ||
			$this->input->post('passcode') != $BBX['bricabox']->invite_code)
		{
			$this->flashy->save_flash('error', 'Sorry, that passcode is wrong. Try again!');
			$this->load->view('bricabox/private', $data);
		}
		else
		{
			$this->Membership_model->add_member($BBX['bricabox']->id, $this->userland->current_user()->id);
			$this->flashy->save_flash('notice', 'Great, you are now a member of this BricaBox. Welcome!');
			header("Location: /");
		}
	}
	
	function request_membership()
	{
		global $BBX;
		
		if ($this->_is_current_user_member())
			header("Location: /");
		
		$this->load->model('Membership_model');
		
		$this->Membership_model->create_application($BBX['bricabox']->id, $this->userland->current_user()->id);
		
		$owner_email = $this->db->query('select email from users where users.id = (select user_id from bricaboxes where bricaboxes.id = ? limit 1)', array($BBX['bricabox']->id))->first_row()->email;
		$this->emailer->deliver_member_request(array(
			'to'		=> $owner_email,
			'subject'	=> "Someone wants to be a member of {$BBX['bricabox']->name}",
			'data'		=> array(
				'data' => array(
					'user' 		=> $this->userland->current_user()->login,
					'url' 		=> bricabox_url($BBX['bricabox']),
					'bricabox'	=> $BBX['bricabox']->name
				)
			)
		));
		
		$this->flashy->save_flash('notice', "Your application to become a member has been received.");
		header("Location: /");
	}
	
	function join_up()
	{
		global $BBX;
		
		if (!$this->userland->logged_in())
		{
			$data['bricabox'] = $BBX['bricabox'];
			$this->load->view('bricabox/guest_join', $data);
		}
		else
		{
			if ($BBX['bricabox']->members_must_apply)
				header("Location: /bricabox/{$BBX['bricabox']->id}/request_membership");
			else
			{
				$this->load->model('Membership_model');
				$this->Membership_model->add_member($BBX['bricabox']->id, $this->userland->current_user()->id);
				$this->flashy->save_flash('notice', 'Great, you are now a member of this BricaBox. Welcome!');
				header("Location: /");
			}
		}
	}
	
	function leave()
	{
		global $BBX;
		
		if ($this->userland->logged_in())
		{
			$this->load->model('Membership_model');
			$this->Membership_model->remove_member($BBX['bricabox']->id, $this->userland->current_user()->login);
			$this->flashy->save_flash('notice', "You are no longer a member of {$BBX['bricabox']->name}.");
		}
		header("Location: /");
	}
	
	function new_bricabox_landing()
	{
		global $BBX;
		
		if (isset($BBX['bricabox']))
			header("Location: ".APP_ROOT_URL."/new");
		
		$query = $this->db->query('select name,id,description from bricaboxes
			where is_seed = 1 and subdomain = ?
			limit 1', array("bricabox_{$this->uri->segment(2)}"));
			
		if ($query->num_rows() == 0)
			show_404();
		else
			$seed_box = $query->first_row();
		
		$data['seed'] = $seed_box;
		header("Location: /bricabox/{$seed_box->id}/clone");
		//$this->load->view('bricabox/new_landing', $data);
	}
	
	function clone_bricabox()
	{
		$id = $this->uri->segment(2);
		
		// load the bricabox's data
		$query = $this->db->query('select * from bricaboxes where id = ? limit 1', array($id));
		if (!$query->num_rows())
			show_404();
			
		$bricabox = $query->first_row();
		$data['bricabox'] = $bricabox;
		
		$this->load->view('bricabox/clone/clone_bricabox', $data);
	}
	
	function create_clone()
	{
		$id = $this->uri->segment(2);
		
		$this->load->model('Bricabox_model');
		$this->load->model('Membership_model');
		
		// load the bricabox's data
		$query = $this->db->query('select * from bricaboxes where id = ? limit 1', array($id));
		if (!$query->num_rows())
			show_404();
		
		$bricabox = $query->first_row();
		$data['bricabox'] = $bricabox;
		
		$params = $this->input->post('bricabox');
		
		if (!$bricabox->can_clone || $this->check_subdomain($params['subdomain']) === true)
		{
			$this->flashy->save_flash('error', "Subdomain is in use; please try another.");
			$this->load->view('bricabox/clone/clone_bricabox', $data);
		}
		else
		{
			// clone it! basically we need to take each attr in $bricabox (instance of stdClass) and
			// create a new assoc. array of params for the new bricabox
			$new_params = array();
			foreach (get_object_vars($bricabox) as $k => $v)
			{
				$new_params[$k] = $v;
			}
			
			// clear values we won't clone
			unset($new_params['id']);
			
			// update attrs where appropriate
			$new_params['user_id'] 		= $this->userland->current_user()->id;
			$new_params['name']			= $params['name'];
			$new_params['subdomain'] 	= strtolower(preg_replace('/[^a-z0-9]/i', '', $params['subdomain']));
			$new_params['created_at'] 	= mysql_now();
			$new_params['updated_at'] 	= $new_params['created_at'];
			$new_params['stat_total_views'] = 0;
			$new_params['custom_domain'] = "";
			$new_params['description']	= "";
			$new_params['use_custom_domain'] = 0;
			$new_params['api_key_google_maps'] = "";
			$new_params['can_clone'] 	= 1;
			$new_params['is_featured']  = 0;
			$new_params['default_wiki_text'] = '';
			$new_params['is_seed']		= 0;
			$new_params['button_url']	= "";
			$new_params['created_from'] = $id;
			$new_params['clone_no_copy_theme'] = 0;
			if ($bricabox->clone_no_copy_theme)
			{
				// don't copy the theme over, so use the default bricabox theme instead
				$new_params['customize_with'] = 'theme';
				$new_params['theme_id']		  = 1;
			}
			
			if ($this->db->insert('bricaboxes', $new_params))
			{
				$new_id  = $this->db->insert_id();
				$new_url = str_replace('://', "://{$new_params['subdomain']}.", APP_ROOT_URL);
				
				// create a membership and upgrade to owner
				$this->Membership_model->add_member($new_id, $this->userland->current_user()->id);
				$this->Membership_model->change_role_by_id($new_id, $this->userland->current_user()->id, 5);
				
				// maps old id -> new id as key-value pair
				$content_type_fix = array();
				
				// copy content types, block instances, and block exclusions
				$query = $this->db->query('select * from content_types where bricabox_id = ?', array($id));
				foreach ($query->result() as $ct)
				{
					$_old_id = $ct->id;
					$content_type_fix[$_old_id] = null;
					
					$ct->bricabox_id = $new_id;
					$ct->id			 = null;
					$this->db->insert('content_types', $ct);
					
					$content_type_fix[$_old_id] = $this->db->insert_id();
				}
				
				$block_inst_fix = array();
				
				$query = $this->db->query('select * from block_instances where bricabox_id = ?', array($id));
				foreach ($query->result() as $bi)
				{
					$_old_id = $bi->id;
					$block_inst_fix[$_old_id] = null;
					
					$bi->bricabox_id = $new_id;
					$bi->id			 = null;
					$this->db->insert('block_instances', $bi);
					
					$block_inst_fix[$_old_id] = $this->db->insert_id();
				}
				
				if (count($block_inst_fix))
				{
					$query = $this->db->query('select * from block_exclusions where block_instance_id in ('.join(',', array_keys($block_inst_fix)).')');
					foreach ($query->result() as $be)
					{
						// this little diddy here updates the exclusion with the new content type and block instance id
						$_ctid = $be->content_type_id;
						$_biid = $be->block_instance_id;
						$be->content_type_id 	= $content_type_fix[$_ctid];
						$be->block_instance_id  = $block_inst_fix[$_biid];
					
						$be->id = null;
						$this->db->insert('block_exclusions', $be);
					}
				}
				
				// send 'em an email
				$owner_email = $this->userland->current_user()->email;
				if (strlen($owner_email))
				{
					$this->emailer->deliver_new_bricabox(array(
						'to'		=> $owner_email,
						'subject'	=> "You've just created a new BricaBox",
						'data'		=> array(
							'data' => array(
								'url' => $new_url
							)
						)
					));
				}
				
				header("Location: {$new_url}");
			}
		}
	}
	
	// if $force_sub is given, returns true if subdomain in use
	function check_subdomain($force_sub = null)
	{
		$sub 	= $force_sub ? $force_sub : $this->input->post('subdomain');
		$query 	= $this->db->query('select id from bricaboxes where subdomain = ? limit 1', array($sub));
		
		if (!$force_sub)
			echo '<span style="line-height: 22px;';
		
		if ($query->num_rows() == 1 || preg_match('/[^-a-z0-9]/i', $sub) || in_array($sub, $this->bricabox->VERBOTEN_SUBDOMAINS))
			if ($force_sub)
				return true;
			else
				echo 'color:#c00;">Sorry, that subdomain is taken.';
		else
			if ($force_sub)
				return false;
			else
				echo 'color:#66bc29;">Great! That subdomain is available.';
			
		if (!$force_sub)
			echo '</span>';
	}
	
	function save_comment()
	{
		global $BBX;
			
		$params = $this->input->post('comment');
		$user_id = $params['user_id'];
		$content_id = $params['content_id'];
		$params['created_at'] = mysql_now();
		$params['updated_at'] = $params['created_at'];
		$this->db->insert('comments', $params);
		
		// Log it to the stream, yo.
		$user_data = $this->db->query('select login,display_name,identity_url from users
			where id = ?', $user_id)->first_row();
		$content_data = $this->db->query('select field1_value from contents
			where id = ?', $content_id)->first_row();
		$this->load->model('Activity_model');
		$this->Activity_model->log_content_comment(array(
			'subject' => username($user_data),
			'object'  => $content_data->field1_value,
			'extra'	  => $params['text'],
			'bricabox_id' => $BBX['bricabox']->id,
			'content_id'  => $content_id
		));
		
		$this->flashy->save_flash('notice', "Great! Your comment has been posted.");
		header("Location: /content/{$content_id}");
	}
	
	function save_wiki()
	{
		global $BBX;
		
		$params['value']  	   = $this->input->post('value');
		$params['instance_id'] = $this->input->post('content_id'); // NOTE: instance_id is really content_id (legacy reason)
		$params['created_at']  = mysql_now();
		$params['updated_at']  = $params['created_at'];
		$params['user_id']	   = $this->userland->current_user()->id;
		$this->db->insert('wiki_versions', $params);
		
		$content_id = $this->input->post('content_id');
		
		$this->flashy->save_flash('notice', "Great! Your changes have been saved.");
		if ($content_id > 0)
			header("Location: /content/{$content_id}");
		else
			header("Location: /");
	}
	
	function save_geocode_data()
	{
		$id 		= $this->uri->segment(2);
		$lat 		= $this->input->post('lat');
		$lng 		= $this->input->post('lng');
		$content_id = $this->input->post('content_id');
		$q = $this->db->query('update contents set geo_lat = ?, geo_lon = ?
			where id = ? and bricabox_id = ?', array($lat, $lng, $content_id, $id));
		echo $q;
	}
	
	function random()
	{
		$this->load->database();
		
		// return a random public bricabox with 10+ entries
		$query = $this->db->query('select subdomain from bricaboxes
		where privacy > 0
			and
				(select count(*) as count_all from contents
					where contents.bricabox_id = bricaboxes.id) >= 10
		order by rand()
		limit 1');
		$url = str_replace('://', "://{$query->first_row()->subdomain}.", APP_ROOT_URL);
		header("Location: {$url}");
		exit();
	}
	
	function delete()
	{
		global $BBX;
		if (!isset($BBX['bricabox']))
		{
			show_404();
			exit();
		}
		$data['bricabox'] = $BBX['bricabox'];
		$data['id']		  = $this->uri->segment(2);
		$this->load->view('bricabox/delete', $data);
	}
	
	function delete_bricabox()
	{
		global $BBX;
		
		$id 	 = $BBX['bricabox']->id;
		$user_id = $this->userland->current_user()->id;
		
		// validate the check param
		$valid_check = md5($id.$user_id);
		$check		 = $this->input->post('check');
		
		if ($check != $valid_check)
		{
			$this->flashy->save_flash('error', "You're not allowed to delete this BricaBox.");
			header("Location: /");
			exit();
		}
		else
		{
			$delete_from = array(
				'bricaboxes' 			=> 'id',
				'block_instances' 		=> 'bricabox_id',
				'categories' 			=> 'bricabox_id',
				'content_types' 		=> 'bricabox_id',
				'contents' 				=> 'bricabox_id',
				'memberships' 			=> 'bricabox_id',
				'memberapplications' 	=> 'bricabox_id'
			);
			$sql = array();
			foreach ($delete_from as $table => $fk)
				$sql[] = "DELETE FROM {$table} WHERE {$fk} = ?";
			
			foreach ($sql as $query)
				$this->db->query($query, $id);
				
			$this->flashy->save_flash('notice', "Your {$BBX['bricabox']->name} BricaBox has been deleted.");
			header("Location: ".APP_ROOT_URL."/person/{$this->userland->current_user()->login}");
			exit();
		}
	}
	
	function toggle_featured()
	{
		if (!$this->userland->logged_in() || !$this->userland->current_user()->is_admin)
		{
			show_404();
			exit();
		}
		
		global $BBX;
		$BBX['bricabox']->is_featured = !$BBX['bricabox']->is_featured;
		$feat = (int)$BBX['bricabox']->is_featured;
		$this->db->query('update bricaboxes set is_featured = ? where id = ? limit 1', array($feat, $BBX['bricabox']->id));
		header("Location: /");
		exit();
	}
	
	function _is_current_user_member()
	{
		global $BBX;
		
		$this->load->model('Membership_model');
		
		if (!$this->userland->logged_in())
			return false;
			
		if ($this->Membership_model->is_member($BBX['bricabox']->id))
			return true;
	}
	
	public function all_activity()
	{
		show_404();
		exit();
		//global $BBX;
		//
		//$this->load->model('Bricabox_model');
		//$this->load->model('Block_model');
		//$this->load->model('Content_model');
		//$this->load->model('Membership_model');
		//$this->load->model('Activity_model');
		//$data['bricabox'] = $BBX['bricabox'];
		//$data['activity'] = $this->Activity_model->get_activity(array('bricabox_id' => $BBX['bricabox']->id));
		//$this->load->view('bricabox/activity', $data);
	}
	
	public function add_link()
	{
		$back_to = $this->input->server('HTTP_REFERER');
		foreach (array('url', 'title', 'rel') as $v)
		{
			$var  = "link_{$v}";
			$$var = $this->input->post($var);
		}
		if (!$link_url)
		{
			$this->flashy->save_flash('error', 'You can\'t add a blank link.');
			header("Location: {$back_to}");
			exit;
		}
		
		$instance_id	= $this->input->post('instance_id');
		$content_id		= $this->input->post('content_id');
		
		$link_url = prep_url($link_url);
		
		$this->db->query("INSERT INTO link_list VALUES(NULL,?,?,?,?,?,NOW())",
			array(
				$instance_id,
				$content_id,
				$link_url,
				$link_title,
				$link_rel
			)
		);
		
		$this->flashy->save_flash('notice', 'Link added.');
		header("Location: {$back_to}");
		exit;
	}
	
	public function remove_link()
	{
		$bricabox_id 	= $this->uri->segment(5);
		$link_id 		= $this->uri->segment(4);
		$hash 			= $this->uri->segment(6);
		
		$back_to = $this->input->server('HTTP_REFERER');
		
		
		$check = md5('w00p'.$link_id.$bricabox_id.$this->userland->current_user()->id);
		
		if ($check != $hash)
		{
			show_404();
			exit;
		}
		
		$this->db->query("DELETE FROM link_list WHERE id = ? LIMIT 1", $link_id);
		
		$this->flashy->save_flash('notice', 'Link removed.');
		header("Location: {$back_to}");
		exit;
	}
	
	public function save_featured_block()
	{
		global $BBX;
		
		require_once APPPATH . 'libraries/blocks/block_instance.php';
		
		$params  = serialize($_POST);
		$inst_id = $this->input->post('id');
		$bbx_id  = $BBX['bricabox']->id;
		
		$back_to = $this->input->post('return_to');
		
		// Save settings
		$this->load->database();
		$this->db->query("DELETE FROM meta_settings WHERE bricabox_id = ? AND block_instance_id = ? LIMIT 1",
			array($bbx_id, $inst_id));
		$this->db->query("INSERT INTO meta_settings (bricabox_id,block_instance_id,name,value,created_at)
			VALUES(?,?,?,?,NOW())",
			array($bbx_id, $inst_id, 'featured_content', $params));
		
		// Return back
		header("Location: {$back_to}");
		exit;
	}
	
	public function save_vcard()
	{
		$params = $this->input->post('vcard', true);
		
		$this->load->database();
		$inst_id = $this->input->post('save_id');
		$query   = $this->db->query("SELECT * FROM vcard_data WHERE instance_id = ? LIMIT 1", $inst_id);
		if ($query->num_rows() == 1)
			$this->db->update('vcard_data', $params, array('instance_id' => $inst_id));
		else
		{
			$params['instance_id'] = $inst_id;
			$this->db->insert('vcard_data', $params);
		}
		
		$back_to = $this->input->post('return_to');
		
		// Return back
		header("Location: {$back_to}");
		exit;
	}
}
?>